package cn.rentaotao.spring.config;

import cn.rentaotao.spring.security.WebSecurityConfig;
import cn.rentaotao.spring.websocket.stomp.WebSocketStompConfig;
import cn.rentaotao.spring.websocket.stomp.WebSocketStompSecurityConfig;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import java.nio.charset.StandardCharsets;

/**
 * Java 初始化器
 * <p>用来代替 web.xml，只能在 servlet3.0 之后使用，一般 tomcat7 就已经支持了
 *
 * <p>在启动的时候会在类路径下寻找 {@link org.springframework.web.WebApplicationInitializer} 的实现类
 *
 * @author rtt
 * @date 2022/5/11 09:30
 */
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * 加载 spring 容器
     *
     * @return 配置类
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{RootConfig.class, WebSecurityConfig.class};
    }

    /**
     * 加载 springMVc 容器配置
     *
     * @return 配置类
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebConfig.class, WebSocketStompConfig.class, WebSocketStompSecurityConfig.class};
    }

    /**
     * 将 DispatchServlet 映射到 "/"
     *
     * @return 映射路径
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }


    /**
     * 定制化 DispatcherServlet
     *
     * @param registration 动态注册信息
     */
    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {

        /*
            可以通过不同的构造器创建 MultipartConfigElement
         */
        registration.setMultipartConfig(new MultipartConfigElement("resources", 2097152, 4194304, 4194304));

        registration.setInitParameter("dispatchOptionsRequest", "true");
    }

    /**
     * 获取需要注册的 Filter，与 DispatcherServlet 的拦截路径一致
     *
     * @return Filter 数组
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(StandardCharsets.UTF_8.displayName());

        return new Filter[] {characterEncodingFilter};
    }

}
